const Router = require('koa-router');
const router = new Router({
  prefix: '/api/admin'
});
const db = require('../../db');
const path = require('path');
const fs = require('fs');

// 获取教师个人信息
router.get('/profile/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const sql = `
      SELECT id, username, name, title, email, phone, avatar, description
      FROM teachers
      WHERE id = ?
    `;
    const [teacher] = await db.query(sql, [id]);
    
    if (teacher) {
      ctx.body = {
        code: 0,
        data: teacher
      };
    } else {
      ctx.body = {
        code: 1,
        msg: '教师不存在'
      };
    }
  } catch (error) {
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 更新教师个人信息
router.put('/profile/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const { username, name, title, email, phone, description, avatar } = ctx.request.body;
    
    // 构建更新字段和值
    const updateFields = [];
    const values = [];
    
    // 只更新非空字段
    if (username !== undefined) {
      updateFields.push('username = ?');
      values.push(username);
    }
    if (name !== undefined) {
      updateFields.push('name = ?');
      values.push(name);
    }
    if (title !== undefined) {
      updateFields.push('title = ?');
      values.push(title);
    }
    if (email !== undefined) {
      updateFields.push('email = ?');
      values.push(email);
    }
    if (phone !== undefined) {
      updateFields.push('phone = ?');
      values.push(phone);
    }
    if (description !== undefined) {
      updateFields.push('description = ?');
      values.push(description);
    }
    if (avatar !== undefined) {
      updateFields.push('avatar = ?');
      values.push(avatar);
    }
    
    // 添加ID到values数组
    values.push(id);

    console.log('更新数据:', ctx.request.body); // 添加日志
    
    // 如果有需要更新的字段
    if (updateFields.length > 0) {
      const sql = `
        UPDATE teachers
        SET ${updateFields.join(', ')}
        WHERE id = ?
      `;
      
      console.log('执行的SQL:', sql); // 添加日志
      console.log('SQL参数:', values); // 添加日志
      
      await db.query(sql, values);
      
      // 获取更新后的数据
      const [updatedTeacher] = await db.query(
        'SELECT id, username, name, title, email, phone, avatar, description FROM teachers WHERE id = ?',
        [id]
      );
      
      ctx.body = {
        code: 0,
        msg: '更新成功',
        data: updatedTeacher
      };
    } else {
      ctx.body = {
        code: 1,
        msg: '没有提供任何需要更新的字段'
      };
    }
  } catch (error) {
    console.error('更新教师信息错误:', error);
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

// 头像上传接口
router.post('/upload/avatar/:id', async (ctx) => {
  try {
    const { id } = ctx.params;
    const file = ctx.request.files.avatar;
    
    // 确保文件是图片
    if (!file.mimetype.startsWith('image/')) {
      throw new Error('只允许上传图片文件！');
    }

    // 生成文件名
    const ext = path.extname(file.originalFilename);
    const fileName = `teacher-${Date.now()}${ext}`;
    
    // 移动文件到目标目录
    const reader = fs.createReadStream(file.filepath);
    const targetPath = path.join(__dirname, '../../public/uploads/images/teachers', fileName);
    const writer = fs.createWriteStream(targetPath);
    reader.pipe(writer);

    // 更新数据库
    const avatarUrl = `/uploads/images/teachers/${fileName}`;
    await db.query(
      'UPDATE teachers SET avatar = ? WHERE id = ?',
      [avatarUrl, id]
    );

    ctx.body = {
      code: 0,
      data: {
        url: avatarUrl
      },
      msg: '头像上传成功'
    };
  } catch (error) {
    ctx.body = {
      code: 1,
      msg: error.message
    };
  }
});

module.exports = router; 